package com.googlecode.openrtp.grizzly.session;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import com.googlecode.openrtp.spi.Key;
import com.googlecode.openrtp.spi.RtpSession;

/**
 *
 * @author jocke
 */
public final class DelayedSession implements Delayed {

    private final RtpSession session;
    private final Key<Long> Key;

    public DelayedSession(Key Key, RtpSession session) {
        this.Key = Key;
        this.session = session;
    }

    public RtpSession getSession() {
        return session;
    }
    
    public PacketGenerator getPacketGenerator() {
        return (PacketGenerator) session;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(session.lookup(Key) - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        } else {
            return Long.compare(this.getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS));
        }
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 23 * hash + Objects.hashCode(this.session);
        return hash;
    }

    @Override
    public String toString() {
        return "DelayedSession{" + "session=" + session + "delay=" + getDelay(TimeUnit.MILLISECONDS) + " }";
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final DelayedSession other = (DelayedSession) obj;
        if (!Objects.equals(this.session, other.session)) {
            return false;
        }
        return true;
    }
}
